<template>
  <div
    class="scroll-container"
    @scroll="handleScroll"
    ref="scrollContainer"
    :style="{
      height: height + 'px',
    }"
  >
    <!-- 占位元素，用于撑开滚动条高度 -->
    <div class="phantom" :style="{ height: totalHeight + 'px' }"></div>
    <!-- 实际渲染的列表区域 -->
    <div class="list" :style="{ transform: `translateY(${offset}px)` }">
      <div
        v-for="item in visibleData"
        :key="item.id"
        class="list-item"
        :style="{ height: itemHeight + 'px' }"
      >
        <slot :item="item"></slot>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    data: Array, // 全部数据源
    itemHeight: { type: Number, default: 50 }, // 每项高度
    visibleCount: { type: Number, default: 10 }, // 可视数量
  },
  data() {
    return {
      startIndex: 0, // 起始索引
      offset: 0, // 列表偏移量
    };
  },
  computed: {
    height() {
      return this.data.length < this.visibleCount
        ? this.data.length * this.itemHeight
        : this.visibleCount * this.itemHeight;
    },
    // 可视区域数据（截取当前需要显示的10条）
    visibleData() {
      return this.data.slice(
        this.startIndex,
        this.startIndex + this.visibleCount
      );
    },
    // 总高度（用于生成滚动条）
    totalHeight() {
      return this.data.length * this.itemHeight;
    },
  },
  methods: {
    handleScroll() {
      const scrollTop = this.$refs.scrollContainer.scrollTop;
      // 计算当前起始索引
      this.startIndex = Math.floor(scrollTop / this.itemHeight);
      // 计算列表偏移量（保持滚动连续性）
      this.offset = this.startIndex * this.itemHeight;
    },
  },
};
</script>

<style scoped>
.scroll-container {
  overflow-y: auto;
  position: relative;
}
.phantom {
  position: absolute;
  left: 0;
  right: 0;
  z-index: -1;
}
.list {
  position: absolute;
  left: 0;
  right: 0;
}
.list-item {
  line-height: 1;
}
</style>
